package cn.kgc.javaweb.servlet;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.javaweb.entity.Student;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/3/23
 */
@WebServlet("/import")
public class ImportServlet  extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        //解析上传的请求参数
        try {
            //解析请求 获取表单中携带的数据 封装成了FileItem
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);

            fileItems.forEach(fileItem -> {

                try {
                    InputStream is = fileItem.getInputStream();
                    ImportParams ips= new ImportParams();
                    //设置标题行占用的行数
                    ips.setTitleRows(1);
                    //设置表格的字段占用的行数
                    ips.setHeadRows(1);
                    //easypoi中数据导入的工具类
                    List<Student> students = ExcelImportUtil.importExcel(is, Student.class, ips);
                    //遍历集合
                    students.forEach(student -> System.out.println("student = " + student));
                    //TODO 将集合中的数据写入数据库

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });

        } catch (FileUploadException e) {
            e.printStackTrace();
        }


    }
}
